<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="课程目标id" prop="coureassessId">
        <el-input v-model="queryParams.coureassessId" placeholder="请输入课程目标id" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="评价名字" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入评价名字" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
     <!-- <el-col :span="1.5">
       <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
         v-hasPermi="['score:course:import']">导入学生评价成绩</el-button>
     </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['score:student:export']">导出评价报告</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
	  v-if="refreshTable"
	 v-loading="loading" :data="filteredScoreList"
	  row-key="id"
	:default-expand-all="isExpandAll"
	:tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程目标" align="center" prop="coureassess.courseassess" />
      <el-table-column label="评价名字" align="center" prop="name" />
      <el-table-column label="占比率" align="center" prop="percent" />
      <el-table-column label="评价内容及方法" align="center" prop="content" />
      <el-table-column label="教师姓名" align="center" prop="teacherName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

		<template slot-scope="scope">
			<!-- <div v-if="scope.row.parentId!=0  "> -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['score:student:edit']" v-if="scope.row.children==null || scope.row.children.length === 0">修改</el-button>
			<el-button
			  size="mini"
			  type="text"
			  icon="el-icon-plus"
			  @click="handleAdd(scope.row)"
			  v-hasPermi="['system:menu:add']"
			  v-if="scope.row.children.length !==0"
			>新增</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['score:student:remove']" v-if="scope.row.children==null || scope.row.children.length === 0">删除</el-button>
       <!-- </div> -->
		</template>

      </el-table-column>
    </el-table>

   <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" / -->>

    <!-- 添加或修改学生管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="评价名字" prop="meataclassId">
          <el-select v-model="form.meataclassId" filterable placeholder="请选择行政班级">
            <el-option v-for="item in metaclassList" :key="item.meataclassId" :label="item.metaclassName"
              :value="item.meataclassId" :disabled="item.status == 1"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="是否删除" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入是否删除" />
        </el-form-item> -->
       <el-form-item label="课程目标" prop="parentId">
         <treeselect
           v-model="form.coureassessId"
           :options="Options"
           :normalizer="normalizer"
           :show-count="true"
           placeholder="选择课程目标"
         />
       </el-form-item>
	   <el-form-item label="评价名字" prop="name">
	     <el-input v-model="form.name" placeholder="请输入评价名字" />
	   </el-form-item>
        <el-form-item label="占比率" prop="percent">
          <el-input v-model="form.percent" placeholder="请输入占比率" />
        </el-form-item>
        <el-form-item label="评价内容及方法" prop="content">
          <el-input v-model="form.content" placeholder="请输入评价内容及方法" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

	<!-- 用户导入对话框 -->
	<el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
	  <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
	    :action="upload.url " :disabled="upload.isUploading"
	    :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
	    <i class="el-icon-upload"></i>
	    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
	    <div class="el-upload__tip text-center" slot="tip">
	     <!-- <div class="el-upload__tip" slot="tip">
	        <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
	      </div> -->
	      <span>仅允许导入xls、xlsx格式文件。</span>
	     <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
	        @click="importTemplate">下载模板</el-link> -->
	    </div>
	  </el-upload>
	  <div slot="footer" class="dialog-footer">
	    <el-button type="primary" @click="submitFileForm">确 定</el-button>
	    <el-button @click="upload.open = false">取 消</el-button>
	  </div>
	</el-dialog>
  </div>
</template>

<script>
import {list,listAll,add,update,deleteInfo,getCourseassessName} from '@/api/score/courseassessName'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getTeacher} from '@/api/score/teacher'
import { getToken } from "@/utils/auth";
export default {
  name: "Student",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedCourseclassStudent: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
	  // 是否展开，默认全部折叠
	  isExpandAll: false,
      // 学生管理表格数据
      scoreList: [],
     refreshTable: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
	  Options:[],
	  teacherId:null,
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
        coureassessId: null,
        name: null,
		courseId:this.$route.query.courseId,
        // percent: null,
        // content: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
	  upload: {
	    // 是否显示弹出层（用户导入）
	    open: false,
	    // 弹出层标题（用户导入）
	    title: "",
	    // 是否禁用上传
	    isUploading: false,
	    // 是否更新已经存在的用户数据
	    updateSupport: 0,
	    // 设置上传的请求头部
	    headers: { Authorization: "Bearer " + getToken() },
	    // 上传的地址
	    url: process.env.VUE_APP_BASE_API + "/score/import"
	  },
    };
  },
  computed: {
    // Filter out the rows where name is '达成度（%）'
    filteredScoreList() {
      return this.scoreList.filter(item => {
        if (item.children) {
          // Filter children as well
          item.children = item.children.filter(child => child.name !== "达成度（%）");
        }
        return item.name !== "达成度（%）";
      });
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学生管理列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then(response => {
		  console.log(response)
        // this.scoreList = this.handleTree(response.data,"id").filter(item => item.name !== '达成度（%）')
        this.scoreList = response.data
        console.log(this.scoreList)
        // this.total = response.total;

        this.loading = false;
      });
     },
	 /** 转换菜单数据结构 */
	 normalizer(node) {
		 console.log(node)
	   if (node.children && !node.children.length) {
	     delete node.children;
	   }
	   return {
	     id: node.id,
	     label: node.name,
	     children: node.children
	   };
	 },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        coureassessId: null,
        name: null,
        percent: null,
        content: null
      };
      this.resetForm("form");
    },
	// getTreeselect() {
	//   listAll().then(response => {
	//     this.Options = [];
	//     const menu = { id: 0, name: '主类目', children: [] };
	//     menu.children = this.handleTree(response.data, "id");
	//     this.Options.push(menu);
	//   });
	// },
getTreeselect() {
  listAll().then(response => {
    // 1. 获取所有课程目标ID（去重）
    const courseAssessIds = [...new Set(response.data.map(item => item.coureassessId))];

    // 2. 为每个课程目标创建顶层节点
    const topLevelNodes = courseAssessIds
      .filter(id => id !== null) // 过滤掉null
      .map(id => {
        // 找到该课程目标的第一个节点获取名称
        const firstItem = response.data.find(item => item.coureassessId === id);
        return {
          id: id, // 使用coureassessId作为ID
          name: firstItem?.coureassess?.courseassess || `课程目标${id}`,
          children: []
        };
      });

    // 3. 构建Treeselect需要的结构
    this.Options = [{
      id: 0,
      name: '目标列表',
      children: topLevelNodes
    }];

    console.log("生成的Options:", this.Options); // 调试用
  });
},
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.studentId)
    //   this.single = selection.length !== 1
    //   this.multiple = !selection.length
    // },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
	  this.form.coureassessId=row.coureassessId
	  this.form.courseId=this.queryParams.courseId
	  this.getTreeselect()
	  if (row != null && row.menuId) {
	    this.form.parentId = row.menuId;

	  } else {
	    this.form.parentId = 0;
	  }
      this.open = true;
      this.title = "添加评价成绩管理";
    },
    // /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset();
	  // this.getTreeselect()
    //   const id = row.id || this.ids
    //   getCourseassessName(id).then(response => {

    //     this.form = response.data;
		// this.form.percent=parseInt(response.data.percent)
		//  console.log(response.data)
    //     this.open = true;
    //     this.title = "修改评价成绩管理";
    //   });
    // },

//     handleUpdate(row) {
//   this.reset();
//   this.getTreeselect(); // 获取课程目标树形数据

//   const id = row.id || this.ids;
//   getCourseassessName(id).then(response => {
//     this.form = {
//       ...response.data,
//       percent: parseInt(response.data.percent),
//       // 确保传递 coureassessId 用于修改所属课程目标
//       originalCoureassessId: response.data.coureassessId // 保存原始值用于比较
//     };

//     console.log("修改表单数据:", this.form);
//     this.open = true;
//     this.title = "修改评价成绩管理";
//   });
// },
//     /** 提交按钮 */
//     submitForm() {
//       this.$refs["form"].validate(valid => {
//         if (valid) {
//       // 构造提交数据
//       const submitData = {
//         ...this.form,
//         // 确保传递 coureassessId
//         coureassessId: this.form.coureassessId || this.form.originalCoureassessId
//       };

//       // 删除临时字段
//       delete submitData.originalCoureassessId;

//           if (this.form.id != null) {
// 			  console.log(this.form)
//             update(this.form).then(response => {
//               this.$modal.msgSuccess("修改成功");
//               this.open = false;
//               this.getList();
//             });
//           } else {
// 			  console.log(this.form)
//             add(this.form).then(response => {
//               this.$modal.msgSuccess("新增成功");
//               this.open = false;
//               this.getList();
//             });
//           }
//         }
//       });
//     },
handleUpdate(row) {
  this.reset();
  this.getTreeselect(); // 获取课程目标树形数据

  const id = row.id || this.ids;
  getCourseassessName(id).then(response => {
    this.form = {
      ...response.data,
      percent: parseInt(response.data.percent),
      // 保存原始coureassessId用于比较
      originalCoureassessId: response.data.coureassessId
    };
    console.log("修改表单数据:", this.form);
    this.open = true;
    this.title = "修改评价成绩管理";
  });
},

/** 提交按钮 */
submitForm() {
  this.$refs["form"].validate(valid => {
    if (valid) {
      // 构造正确的提交数据
      const submitData = {
        ...this.form,
        coureassessId: this.form.coureassessId || this.form.originalCoureassessId
      };

      // 删除临时字段
      delete submitData.originalCoureassessId;

      console.log("实际提交数据:", submitData); // 调试用

      if (submitData.id != null) {
        update(submitData).then(response => {  // 关键修改：使用submitData而不是this.form
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        add(submitData).then(response => {  // 关键修改：使用submitData而不是this.form
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    }
  });
},
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除评价成绩编号为"' + id + '"的数据项？').then(function () {
        return deleteInfo(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },




    /** 复选框选中数据 */
    handleCourseclassStudentSelectionChange(selection) {
      this.checkedCourseclassStudent = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('score/courseAssessName/export', {
        ...this.queryParams
      }, `课程目标达成情况评价报告.docx`)
    },
	/** 导入按钮操作 */
	handleImport() {
	  this.upload.title = "导入学生成绩";
	  this.upload.open = true;
	},
	/** 下载模板操作 */
	// importTemplate() {
	//   this.download('niuyabo/course/importTemplate', {
	//   }, `course_template_${new Date().getTime()}.xlsx`)
	// },
	// 文件上传中处理
	handleFileUploadProgress(event, file, fileList) {
	  this.upload.isUploading = true;
	},
	// 文件上传成功处理
	handleFileSuccess(response, file, fileList) {
	  this.upload.open = false;
	  this.upload.isUploading = false;
	  this.$refs.upload.clearFiles();
	  this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
	  this.getList();
	},
	// 提交上传文件
	submitFileForm() {
	  this.$refs.upload.submit();
	}

  }

};
</script>
